package easy;

public class Solution_1496 {

    public boolean isPathCrossing(String path) {
        int[][] counts = new int[path.length()][2];
        char[] array = path.toCharArray();
        for (int i = 0; i < array.length; i++) {
            char c = path.charAt(i);
            if (i>0) {
                counts[i][0] = counts[i-1][0];
                counts[i][1] = counts[i-1][1];
            }
            if (c == 'N') {
                counts[i][1]++;
            } else if (c == 'S') {
                counts[i][1]--;
            } else if (c == 'E') {
                counts[i][0]++;
            } else if (c == 'W') {
                counts[i][0]--;
            }
            if (counts[i][0]==0 && counts[i][1]==0) {
                return true;
            }
            for (int j = i - 4; j >= 0; j -= 4) {
                if ((counts[i][0] - counts[j][0]) == 0 && (counts[i][1] - counts[j][1]) == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    /*public boolean isPathCrossing(String path) {
        int aa = 0, bb = 0, cc = 0, dd = 0;
        for (int i = 0; i < path.length(); i++) {
            char c = path.charAt(i);
            if (c == 'N') {
                aa++;
            } else if (c == 'S') {
                bb++;
            } else if (c == 'E') {
                cc++;
            } else if (c == 'W') {
                dd++;
            }
        }
        int a1 = aa + bb + 1, b1 = cc + dd + 1;
        boolean[][] flags = new boolean[a1][b1];
        flags[bb][dd] = true;
        for (int i = 0, row = bb, col = dd; i < path.length(); i++) {
            char c = path.charAt(i);
            if (c == 'N') {
                row++;
            } else if (c == 'S') {
                row--;
            } else if (c == 'E') {
                col++;
            } else if (c == 'W') {
                col--;
            }
            if (flags[row][col]) {
                return true;
            }
            flags[row][col] = true;
        }
        return false;
    }*/

    public static void main(String[] args) {
        Solution_1496 model = new Solution_1496();
        System.out.println(model.isPathCrossing("N"));
        System.out.println(model.isPathCrossing("NES"));
        System.out.println(model.isPathCrossing("NESWW"));
    }
}
